<template>
  <el-dialog v-model="dialogTableVisible" title="绑定邮箱">
    <el-form>
      <el-form-item label="邮箱">
        <el-input placeholder="请输入绑定邮箱" v-model="userInfoForm.userEmail"></el-input>
      </el-form-item>
      <el-form-item align="center">
        <el-button type="primary" size="large" @click="updateUserEmail">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog v-model="dialogForgetVisible" title="绑定邮箱">
    <el-form
        ref="forgetFormRef1"
        :model="forgetForm"
        :rules="forgetRules1"
        label-position="right"
        label-width="80px"
        align-center
        v-show="isShow">
      <el-form-item label="手机号" prop="userId">
        <el-input v-model="forgetForm.userId" placeholder="请输入手机号" size="large"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="checkCode">
        <el-input
            v-model="forgetForm.checkCode"
            placeholder="请输入验证码"
            autocomplete="off"
            size="large"
        >
          <template #append>
            <el-button @click="getCode">获取验证码</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-submit" @click="confirmPhone">确认</el-button>
      </el-form-item>
    </el-form>
    <el-form ref="forgetFormRef2"
             :model="forgetForm"
             :rules="forgetRules2"
             label-position="right"
             label-width="80px"
             align-center
             v-show="!isShow">
      <el-form-item label="密码" prop="userPassword">
        <el-input
            v-model="forgetForm.userPassword"
            type="password"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword">
        <el-input
            v-model="forgetForm.checkPassword"
            type="password"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-submit" @click="updatePass">确认修改</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <div class="user-info">
    <el-row :span="24">
      <!--      用户信息部分-->
      <el-col :span="24">
        <basic-container>
          <div class="user-info__content">
            <div class="user-info__avatar"><img :src="userInfoForm.userAvatar" alt="" /></div>
            <div class="user-info__box">
              <div class="info-title">
                <div class="title">{{userInfoForm.userName}}</div>
                <div class="cert-status" v-if="userInfoForm.userStatus === 2">
                  <img class="auth-icon" src="../../img/auth.png"><p>已实名认证</p>
                </div>
                <div class="cert-status" v-else>
                  <router-link to="/info/certification">
                    <img class="auth-icon" src="../../img/unauth.png"><p>未实名认证，点击立即认证</p>
                  </router-link>
                </div>
              </div>
              <div class="info-name">
                <div class="name-text">证件号</div>
                <div class="ID-num" v-if="userInfoForm.userStatus === 2">{{ hideIdNum }}</div>
                <div class="cert-status" v-else>未实名认证</div>
              </div>
              <div class="info-power">
                <div class="power-title">角色权限</div>
              </div>
            </div>
          </div>
        </basic-container>
      </el-col>


      <!--      用户设置部分-->
      <el-col :span="24">
        <basic-container>
          <div class="user-info__main">
            <div class="account-section">

              <!-- ====================== 用户设置部分 —— ① 登录设置 ====================== -->
              <div class="account-section-item item-left">
                <div class="title-ctnr">
                  <span class="title-main">登录设置</span>
                  <span class="title-doc">用于登录当前账号</span>
                </div>
                <div class="body-ctnr">
                  <!-- ① 登录设置 -【手机号】 -->
                  <div class="row-item">
                    <div class="label">手机号</div>
                    <div class="content">
                      <div class="status">{{hidePhoneNum}}</div>
                    </div>
                  </div>
                  <!-- ① 登录设置 -【邮箱】 -->
                  <div class="row-item">
                    <div class="label">邮箱</div>
                    <div class="content">
                      <div class="status notSet" v-if="validatenull(userInfoForm.userEmail)">未设置</div>
                      <div class="status" v-else>{{userInfoForm.userEmail}}</div>
                      <div class="handle">
                        <div @click="dialogTableVisible = true">
                          <span v-if="validatenull(userInfoForm.userEmail)">立即设置</span>
                          <span v-else>修改</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- ① 登录设置 -【登录密码】 -->
                  <div class="row-item">
                    <div class="label">登录密码</div>
                    <div class="content">
                      <div class="status">******</div>
                      <div class="handle">
                        <div>
                          <span @click="dialogForgetVisible = true">修改</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- ====================== 用户设置部分 —— ② 签署设置 ====================== -->
              <div class="account-section-item item-right">
                <div class="title-ctnr">
                  <span class="title-main">签署设置</span>
                  <span class="title-doc">在文件签署环节用于表达您真实的签署意愿</span>
                </div>
                <div class="body-ctnr">
                  <!-- ② 签署设置 -【签署密码】 -->
                  <div class="row-item">
                    <div class="label">签署密码</div>
                    <div class="content">
                      <div :class="1===1?'status notSet':'status'">未设置</div>
                      <div class="handle">
                        <div>
                          <span v-if="1===1">立即设置</span>
                          <span v-else>修改</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </basic-container>
      </el-col>

    </el-row>

  </div>
</template>

<script setup>

import {ref,getCurrentInstance} from 'vue';
import {getUserInfo, updateUserEmailApi} from '../../api/user';
import '../../styles/user-info.scss'
import {ElMessage} from 'element-plus';
import {validatenull} from '../../utils/validate';
import {checkPhoneApi, getCodeApi, updateUserPassApi} from '../../api/login';
import {useStore} from 'vuex';
const {proxy} = getCurrentInstance()

const dialogTableVisible = ref(false)

const userInfoForm = ref({
  userId: '',
  userName: '',
  userStatus: 1,
  userAvatar: '',
  userEmail: '',
  userIdCard: ''
})

const hidePhoneNum = ref("00000000000")
const hideIdNum = ref("")

const store = useStore()
/**
 * 获取用户信息
 */
const getUserInformation = ()=>{
  getUserInfo(store.getters.userId).then(res=>{
    let data = res.data.result
    userInfoForm.value = data
    hidePhoneNum.value = hidePhone(userInfoForm.value.userId)
    if(!validatenull(userInfoForm.value.userIdCard)){
      hideIdNum.value = hideId(userInfoForm.value.userIdCard);
    }
  })
}
getUserInformation()

/**
 * 隐藏手机号中间四位
 * @param value
 * @returns {`${*}****${*}`}
 */
const hidePhone = (value)=> {
  const start = value.slice(0, 3)
  const end = value.slice(-4)
  return `${start}****${end}`
}


/**
 * 隐藏身份证号
 * @param value
 * @returns {`${*}****${*}`}
 */
const hideId = (value)=> {
  const start = value.slice(0, 2)
  const end = value.slice(-2)
  return `${start}**************${end}`
}

const updateUserEmail = () => {
  updateUserEmailApi(userInfoForm.value).then(res=>{
    if(res.data.result === "success"){
      ElMessage.success("修改成功！")
      dialogTableVisible.value = false
      getUserInformation()
    }else {
      ElMessage.error("修改失败，请重试！")
    }
  })

}


/**
 * 修改密码设置
 */
const dialogForgetVisible = ref(false)

const forgetFormRef1=ref(null)
const forgetFormRef2=ref(null)
const forgetForm = ref({
  userId: '',
  checkCode: '',
  userPassword: '',
  checkPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    if (forgetForm.value.userPassword !== '') {
      if (!forgetFormRef2.value) return
      forgetFormRef2.value.validateField('checkPassword', () => null)
    }
    callback();
  }
};
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== forgetForm.value.userPassword) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const forgetRules1 = ref({
  userId:[
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
    },
    {
      pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  checkCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    }
  ]
})

const forgetRules2 = ref({
  userPassword: [{ validator: validatePass, trigger: 'blur' ,required: true}],
  checkPassword: [{ validator: validatePass2, trigger: 'blur' ,required: true}],
})

const isShow = ref(true)

/**
 * 获取验证码
 */
const getCode = () =>{
  getCodeApi(forgetForm.value.userId).then(res=> {
    if(res.data.responseSuccess){
      ElMessage.success("发送成功！");
    }
  })
}

/**
 * 校验手机号是否正确，如果正确则进入修改密码界面
 */
const confirmPhone = () => {
  forgetFormRef1.value.validate(valid => {
    if (valid) {
      checkPhoneApi(forgetForm.value).then(res=>{
        let data = res.data.result
        if(data === "noExist"){
          ElMessage.error("该用户不存在，请检查手机号是否正确")
          forgetFormRef1.value.resetFields()
        }else if(data === "timeOut"){
          ElMessage.error("验证码已过期，请重新获取")
        }else if(data === "success"){
          ElMessage.success("验证成功，请修改密码")
          isShow.value = !isShow.value
        }else {
          ElMessage.error("验证码错误，请重新获取")
        }
      })

    }
  })
}

const updatePass = () => {
  forgetFormRef2.value.validate(valid => {
    if(valid){
      forgetForm.value.userPassword = proxy.$md5(forgetForm.value.userPassword)
      updateUserPassApi(forgetForm.value)
          .then(res=>{
            let data = res.data.result
            if(data === 'success'){
              ElMessage.success("更改成功！")
              setInterval(function (){
                dialogForgetVisible.value = false
              },3000)
            }else if(data === 'noExist'){
              ElMessage.warning("该用户不存在！请验证手机号！")
              setInterval(function (){
                isShow.value = true
                forgetFormRef1.value.resetFields()
                forgetFormRef2.value.resetFields()
              },2000)
            }else if(res.data.errorMsg === "databaseError"){
              ElMessage.error("修改失败！请稍后再试")
              setInterval(function (){
                isShow.value = true
                forgetFormRef1.value.resetFields()
                forgetFormRef2.value.resetFields()
              },2000)
            }
          })
    }
  })
}

</script>

<style lang="scss">

</style>
